/* 
 * Copyright (C) 2010---2012 星星(wuweixing)<349446658@qq.com>
 * 
 * This file is part of Wabacus 
 * 
 * Wabacus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.wabacus.system.dataimport.filetype;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFName;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import com.wabacus.config.resource.dataimport.configbean.AbsDataImportConfigBean;
import com.wabacus.config.resource.dataimport.configbean.EastDataImportBean;
import com.wabacus.config.resource.dataimport.configbean.EastDataImportConfigBean;
import com.wabacus.config.resource.dataimport.configbean.XlsDataImportBean;
import com.wabacus.exception.WabacusDataImportException;
import com.wabacus.util.Tools;

public class EastFileProcessor extends AbsFileTypeProcessor
{
    private static Log log=LogFactory.getLog(EastFileProcessor.class);

    private BufferedInputStream bis;

    private List<HSSFSheet> sheetList= new ArrayList<HSSFSheet>();

    private List<String> sheetNameList= new ArrayList<String>();

    private HorizontalDataLayout layoutObj;

    private EastDataImportBean eastConfigBean;

    public EastFileProcessor(EastDataImportConfigBean configBean)
    {
        super(configBean);
        eastConfigBean=(EastDataImportBean)configBean;
        layoutObj=new HorizontalDataLayout();
        
    }

    public void init(File datafile)
    {
        try
        {
            bis=new BufferedInputStream(new FileInputStream(datafile));
            POIFSFileSystem fs=new POIFSFileSystem(bis);
            HSSFWorkbook workbook=new HSSFWorkbook(fs);
            int sheetcount = workbook.getNumberOfSheets();
            for(int i=0;i<sheetcount;i++){
            	sheetNameList.add(workbook.getSheetName(i));
            	sheetList.add(workbook.getSheetAt(i));
            }
            if(sheetList.size()<1)
            {
                throw new WabacusDataImportException("在数据文件"+datafile.getAbsolutePath()
                        +"中没有取到所需的sheet");
            }
        }catch(FileNotFoundException e)
        {
            throw new WabacusDataImportException("数据导入失败，没有找到数据文件"+datafile.getAbsolutePath(),e);
        }catch(IOException ioe)
        {
            throw new WabacusDataImportException("导入数据文件"+datafile.getAbsolutePath()+"失败",ioe);
        }
    }

    public int getRecordcount(HSSFSheet sheetObj)
    {
    	layoutObj.init(sheetObj);
        return recordcount;
    }

    
    public boolean isEmpty()
    {
        if(this.recordcount<=0) return true;
        List lstRowDataTmp;
        for(int i=startrecordindex;i<startrecordindex+recordcount;i++)
        {
            lstRowDataTmp=this.getRowData(i);
            if(lstRowDataTmp!=null&&lstRowDataTmp.size()>0) return false;
        }
        return true;
    }

    public List<String> getLstColnameData(HSSFSheet sheetObj)
    {
        return layoutObj.getLstColnameData(sheetObj);
    }

    public List getRowData(HSSFSheet sheetObj,int rowidx)
    {
        if(rowidx<startrecordindex||rowidx>=sheetObj.getLastRowNum()) return null;
        return layoutObj.getRowData(sheetObj,rowidx);
    }

    public void destroy()
    {
        try
        {
            if(bis!=null) bis.close();
        }catch(IOException e)
        {
            log.warn("关闭文件流"+configBean.getFilepath()+"/"+configBean.getFilename()+"失败",e);
        }
    }

    private class HorizontalDataLayout
    {
        public void init(HSSFSheet sheetObj)
        {
        	startrecordindex=eastConfigBean.getStartdatarowindex();
            recordcount=sheetObj.getLastRowNum()-startrecordindex+1;//有效的记录行数
            if(recordcount<0) recordcount=0;
        }

        public List<String> getLstColnameData(HSSFSheet sheetObj)
        {
            List<String> lstResults=new ArrayList<String>();
            int colnamerowindex=eastConfigBean.getColnamerowindex();
            if(colnamerowindex<0) return null;
            HSSFRow row=sheetObj.getRow(colnamerowindex);
            if(row==null) return null;
            int cellcount=row.getLastCellNum()-row.getFirstCellNum();
            if(cellcount<=0) return null;
            HSSFCell cellTmp;
            for(int i=0;i<cellcount;i++)
            {
                cellTmp=row.getCell(i);
                if(cellTmp==null)
                {
                    lstResults.add("");
                }else
                {
                    lstResults.add(cellTmp.getRichStringCellValue().getString());
                }
            }
            return lstResults;
        }

        public List<Object> getRowData(HSSFSheet sheetObj,int recordidx)
        {
            List<Object> lstResults=new ArrayList<Object>();
            HSSFRow row=sheetObj.getRow(recordidx);
            if(row==null) return null;
            int cellcount=row.getLastCellNum()-row.getFirstCellNum();
            if(cellcount<=0) return null;
            HSSFCell cellTmp;
            for(int i=0;i<cellcount;i++)
            {
                cellTmp=row.getCell(i);
                lstResults.add(getCellValue(cellTmp));
            }
            return lstResults;
        }
    }



//        public void init()

//            startrecordindex=xlsConfigBean.getStartdatacolindex();//数据的起始列号
//            HSSFRow row=sheetObj.getRow(xlsConfigBean.getStartdatarowindex());//取到数据第一行

//            int colcnt=row.getLastCellNum()-row.getFirstCellNum();//总列数


//            if(endrecordidx<0||endrecordidx>=colcnt)




//                endrecordindex=endrecordidx;




//        {

//            if(endnamerowidx<=0) return null;//没有数据


//            {//如果配置了字段名列的最后一行行号，且小于最大行数

//            }




//            {




//                }else




//                        lstResults.add("");




//                }




//        public List getRowData(int recordidx)


//            if(enddatarowidx<=0) return null;//没有数据


//            {//如果配置了字段名列的最后一行行号，且小于最大行数
//                enddatarowidx=xlsConfigBean.getEnddatarowindex();




//            System.out.println("行号"+recordidx);




//                {




//                    lstResults.add(getCellValue(cellTmp));




//        }


    private Object getCellValue(HSSFCell cell)
    {
        if(cell==null) return null;
        switch (cell.getCellType())
        {
            case HSSFCell.CELL_TYPE_STRING:
                return cell.getRichStringCellValue().getString();
            case HSSFCell.CELL_TYPE_BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case HSSFCell.CELL_TYPE_NUMERIC:
                if(HSSFDateUtil.isCellDateFormatted(cell))
                {
                    return cell.getDateCellValue();
                }else
                {
                    return String.valueOf(cell.getNumericCellValue());
                    /*double d=cell.getNumericCellValue();
                    if(d-(int)d<Double.MIN_VALUE)
                    { 
                        return (int)d;
                    }else
                    { // 是否为double型  
                        return cell.getNumericCellValue();
                    }*/
                }
            case HSSFCell.CELL_TYPE_BLANK:
                return "";
            default:
                return null;
        }
    }

	/* (non-Javadoc)
	 * @see com.wabacus.system.dataimport.filetype.AbsFileTypeProcessor#getLstColnameData()
	 */
	@Override
	public List<String> getLstColnameData() {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.wabacus.system.dataimport.filetype.AbsFileTypeProcessor#getRowData(int)
	 */
	@Override
	public List getRowData(int rowidx) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 获取sheetList
	 * @return sheetList
	 */
	public List<HSSFSheet> getSheetList() {
		return sheetList;
	}

	/**
	 * 设置sheetList的值为sheetList
	 * @param sheetList
	 */
	public void setSheetList(List<HSSFSheet> sheetList) {
		this.sheetList = sheetList;
	}

	/**
	 * 获取sheetNameList
	 * @return sheetNameList
	 */
	public List<String> getSheetNameList() {
		return sheetNameList;
	}

	/**
	 * 设置sheetNameList的值为sheetNameList
	 * @param sheetNameList
	 */
	public void setSheetNameList(List<String> sheetNameList) {
		this.sheetNameList = sheetNameList;
	}
}
